/**
 * 文章
 */
var marked = require('marked');
var Promise = require('bluebird');

module.exports = {
	attributes: {
		// 文章ID
		id: {
			type: "integer",
			autoIncrement: true,
			defaultsTo: 12300
		},
		key: {
			type: "string",
			unique: true
		},
		classify: {
			type: "string",
			unique: true
		},
		tags: {
			type: "string",
			unique: true
		},
		title: {
			type: "string"
		},
		keyword: {
			type: "string"
		},
		description: {
			type: "string"
		},
		body: {
			type: 'string'
		},
		hot: {
			type: "integer"
		},
		bodyHTML: function(){
			return marked(this.body)
		}
	},
	beforeCreate: function(obj, next){

		var attributes = this.attributes;
		var defaultsTo = attributes.id.defaultsTo;
		
		
		if (obj.classify && obj.tags){
			// 必须确保classify 和tags 在数据库里面
			return Promise.join(Classify.findOne({
					key: obj.classify
				}),Tags.findOne({
					key: obj.tags
			})).spread(function(c,t){
				if ( c && t) {
					// 更新自增键
				    Article.count().exec(function(err, cnt){
				    	
				    	if (null == err) {
				    		obj.id = defaultsTo + cnt + 1;
				    		obj.key = 'uniq' + (obj.key || obj.id.toString(36));
				    	
					    	//更新classify 和tags 热度
					    	Promise.join(Classify.update({
						    		key: c.key
						    	},{
						    		heat: c.heat +1
						    }), Tags.update({
						    		key: t.key
						    	},{
						    		heat: t.heat +1
					    	})).spread(function(ce,te){
					    		next();
					    	})
				    	}
				    	next(err);
				    });
				} else {
					next("db no classify or tags");
				}
			})
		} else {
			next("input no classify or tags");
		}

	},
	afterCreate: function(obj, next){

		Promise.join(Classify.update({key:obj.classify},{

		}))
		
	}

}